//
//  YBRequestManager.m
//  1518_69_俞槟
//
//  Created by 俞槟 on 15/11/7.
//  Copyright © 2015年 yubin. All rights reserved.
//

#import "MallRequestManager.h"
#import "BaseDataRequest.h"

@implementation MallRequestManager
+(MallRequestManager *)shareManager{
    static MallRequestManager *manager = nil;
    @synchronized(self) {
        if(manager==nil){
            manager=[[MallRequestManager alloc]init];
        }
    }
    return manager;
}

+ (void)post:(NSString *)URL RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{
    //解析请求参数，用NSDictionary来存参数，通过自定义的函数parseParams把它解析成一个post格式的字符串
    NSHTTPCookieStorage *cookieJar =[NSHTTPCookieStorage sharedHTTPCookieStorage];
    for(NSHTTPCookie*cookie in[cookieJar cookies]){
        NSLog(@"cookie%@",cookie);
    }
    // 1.创建请求
    //把传进来的URL字符串转变为URL地址
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASEURL,URL]];
    //请求初始化，可以在这针对缓存，超时做出一些设置
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                    
                                                       timeoutInterval:20
                                    ];
    request.HTTPMethod = @"POST";
    
            // 2.设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            // 3.设置请求体
    NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
            request.HTTPBody = data;
        // 4.发送请求
    //创建一个新的队列（开启新线程）
    NSOperationQueue *queue = [NSOperationQueue new];
    
    //发送异步请求，请求完以后返回的数据，通过completionHandler参数来调用
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:block];
}

+ (NSString *)parseParams:(NSDictionary *)params{
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    //实例化一个key枚举器用来存放dictionary的key
    NSEnumerator *keyEnum = [params keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@"%@=%@&",key,[params valueForKey:key]];
        [result appendString:keyValueFormat];
        NSLog(@"post参数：%@",result);
    }
    return result;
}

//微信支付请求
+ (void)GETWeiXinWith:(NSString *)URL RequestParams:(NSString *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{
    {
        NSString *urlString =[NSString stringWithFormat:@"%@=%@",WeiXinURL,params];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];
        //设置请求方式为get
        [request setHTTPMethod:@"GET"];
        //添加用户会话id
        [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
        //连接发送请求
//        finished = false;
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        //堵塞线程，等待结束
//        while(!finished) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
        //[_waitingDialog dismissWithClickedButtonIndex:0 animated:NO];
//        [connection release];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{
        return NO;
}

//下面两段是重点，要服务器端单项HTTPS 验证，iOS 客户端忽略证书验证。
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
        return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        NSLog(@"didReceiveAuthenticationChallenge %@ %zd", [[challenge protectionSpace] authenticationMethod], (ssize_t) [challenge previousFailureCount]);
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
            [[challenge sender] useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
            [[challenge sender] continueWithoutCredentialForAuthenticationChallenge: challenge];
        }
}

//处理数据 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{ 
}

@end
